<?php
namespace app\common\model;
use app\common\service\MailService;
use app\common\service\SmsService;
use think\Exception;

class SendLog extends TimeModel
{

    protected function getTypeAttr($value){
        switch ($value){
            case 1;
            return '邮件';break;
            case 2:
            return '短信';break;
        }
    }

    private static function checkAuth($object, $objectType = 1)
    {
        if ($objectType == 1) {
            return MailService::checkAuth($object);
        }else{
            return SmsService::checkAuth($object);
        }
    }

    public static function sendCode($toUser, $objectType = 1, $event = 'REG')
    {
        $res = static::checkAuth($objectType, $event);
        if ($res !==true) {
            return array('code' => 0, 'msg' => $res['msg']);
        }
        $code=create_random_str(6,'number');
        try {
            if ($objectType == 1) {
                $ret = MailService::sendEmail($toUser, '验证码 ' . $code, $code);
            } elseif ($objectType == 2) {
                $ret = SmsService::sendSms($toUser, $code, 1);
            }
        }catch(\Exception $e){
            echo $e->getMessage();
            exit();
        }
        if($ret['code']==1){
            $retData=$ret['data'];
            $data['type']=$objectType;
            $data['ip']=request()->ip();
            $data['object']=$toUser;
            $data['event']=$event;
            $data['code']=$code;
            $data['status']=1;
            $data['model']=$retData['model'];
            $data['content']=$retData['content'];
            $data['expire_time']=$retData['expiry_time']*60+time();
            $data['back_msg']=$ret['msg'];
            (new SendLog())->save($data);
        }
        return $ret;
    }

    public static function codeCheck($code, $object, $type=1,$event = 'REG')
    {
        $where['code'] = $code;
        $where['object'] = $object;
        if($type) {
            $where['type'] = $type;
        }
        $where['event'] = $event;
        $where['is_used'] = 0;

        $find = static::where($where)->find();
        if (!$find) {
            return array('code' => 0, 'msg' => '验证码不正确', 'data' => []);
        } elseif ($find->expire_time < time()) {
            return array('code' => 0, 'msg' => '验证码过期,请重新操作', 'data' => []);
        }
        return array('code' => 1, 'msg' => '验证码正确', 'data' => $find->toArray());

    }

    public static function codeSetUsed($id)
    {
        $verificationCode = static::find($id);
        $verificationCode->is_used = 1;
        $verificationCode->save();
    }

}